<?php

namespace App\Auth;

use App\User;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use App\Helpers\ResponseTrait;

/**
 * Created by PhpStorm.
 * User: hans
 * Date: 16/6/2
 * Time: 上午11:44.
 */
class HWTUserProvider
{
    use ResponseTrait;

    /**
     * @var Request
     */
    protected $request;

    /**
     * @var string
     */
    protected $token;

    /**
     * HWTUserProvider constructor.
     *
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        $this->request = $request;

        $this->token = $this->getTokenFromHeader($request);
    }

    /**
     * 判断用户是否为游客身份.
     *
     * @return bool
     */
    public function guest()
    {
        $userId = app('redis')->get('token:all:'.$this->token);

        return $userId === null ? true : false;
    }

    /**
     * @return mixed
     */
    public function user()
    {
        if ($this->guest()) {
            throw new UnauthorizedHttpException(null, 'Cant authorize with your token');
        }


        $userId = app('redis')->get('token:all:'.$this->token);

        return $userId;
    }

    /**
     * 获取用户ID.
     *
     * @return int|null
     */
    public function getUserId()
    {
        if ($this->guest()) {
            throw new UnauthorizedHttpException(null, 'Cant authorize with your token');
        }

        return app('redis')->get('token:all:'.$this->token);
    }
}
